from django.contrib.auth.models import Group
from rest_framework.permissions import *
from django.conf import settings

def is_from_lab_group(user):
    lab_group = Group.objects.get_or_create(name=settings.LAB_GROUP)[0]
    current_groups = user.groups.all()
    if lab_group in current_groups:
        return True
    else:
        return False

class IsOwnerOrAdmin(BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.user is None:
            return False
        if request.user.is_superuser:
            return True
        if request.user == obj.seller:
            return True
        current_groups = request.user.groups.all()
        if request.method in SAFE_METHODS:
            if is_from_lab_group(request.user):
                return True
        elif request.user.is_staff:
            owner_group = obj.seller.groups.all()[0]
            if owner_group in current_groups:
                return True
        return False

class IsLabMemberOrReadOnly(BasePermission):
    def has_permission(self, request, view):
        if request.method in SAFE_METHODS:
            return True
        if request.user.is_superuser:
            return True
        if is_from_lab_group(request.user):
            return True
        return False

